package jxta.chat;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import jxta.chat.events.JxtaChatEvent;
import net.jxta.peergroup.PeerGroup;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.JxtaBiDiPipe;

/**
 * The class is a singelton class that holds a BiDiPipe
 * that had been discovered for all discovered peers 
 */
public class PipeHolder {

	/**
	 * A map that holds a BiDiPipe for a peer.
	 * key - peerName
	 * value - the peers BiDiPipe
	 */
	private Map<String, JxtaBiDiPipe> pipes = null;
	
	private static PipeHolder mInstance = null;
	
	private PipeHolder(){
		pipes = new HashMap<String, JxtaBiDiPipe>();
	}
	
	public static PipeHolder getInstance(){
		
		if (mInstance == null){
			mInstance = new PipeHolder();
		}
		
		return mInstance;
	}
	
	/**
	 * Add a new pipe to the map
	 * 
	 * @param peerName the peer that the pipe belongs to
	 * @param pipe the peers pipe
	 */
	public void addPipe(String peerName, JxtaBiDiPipe pipe){
		pipes.put(peerName, pipe);
	}
	
	public void addPipe(PipeAdvertisement adv, PeerGroup pg, String peerName){
	
        try {
			JxtaBiDiPipe pipe = new JxtaBiDiPipe(pg, adv,
					40 * 1000, null);
			
			pipes.put(peerName, pipe);
		} catch (IOException e) {
			System.out.println("Error creating pipe to peer " + peerName + ". error: " + e.getMessage());
		}		
	}
	
	/**
	 * Returns a pipe for the given peer name 
	 * 
	 * @param peerName the peer that we want to get the pipe for
	 * @return the peers pipe
	 */
	public JxtaBiDiPipe getPipe(String peerName){
		return pipes.get(peerName);
	}
	
	/**
	 * Removes a peer pipe from the map and closes the pipe.
	 * @param peerName the name of the peer we want to remove
	 */
	public void remove(String peerName){
		if (pipes.containsKey(peerName)){
			try {
				pipes.get(peerName).close();
			} catch (IOException e) {
				System.out.println("Error closing pipe. error: " + e.getMessage());
			}
			
			pipes.remove(peerName);
		}
	}
	
	/**
	 * Removes all pipes from the map, and closes them
	 */
	public void removeAll(){
		for (JxtaBiDiPipe pipe : this.pipes.values()){
			try {
				pipe.close();
			} catch (IOException e) {
				System.out.println("Error closing pipe. error: " + e.getMessage());
			}
		}
		
		pipes.clear();
	}
	
}
